#include <map>
#include <vector>
#include <string>

#include <iostream>
#include <sstream>
#include <algorithm>

#include "IdentTable.hpp"


int IdentTable::currentTempIdentNumber = 0;

IdentTable::IdentTable() { 
	this->identTable = new MapStrInt();
	this->revLookupTable = new VectorStr();
}

IdentTable::~IdentTable() { 
	delete identTable;
	delete revLookupTable;
}

/*
 * renvoye un nombre >= 0, le nombre associe au symbole donne
 */
int IdentTable::put(String * name){
	String identName = String(*name);
	std::transform(identName.begin(),  identName.end(),  identName.begin(),  ::tolower);

	MapStrInt::iterator it;

	it = identTable->find( identName );
	if(it != identTable->end()){
		return it->second;
	} else {
		int value = identTable->size();

		(*this->identTable)[identName] = value;
		this->revLookupTable->push_back(identName);
		
//		std::cout << "inserted: " <<identName <<":" << value << std::endl;

		return value;
	}
}
int IdentTable::put(char * identName){
	String temp = String(identName);
	return put(&temp);
}

int IdentTable::putTemp() {

	std::stringstream ss;
	ss << "__temp__" << currentTempIdentNumber;
	String tempIdentName = String(ss.str());
	currentTempIdentNumber++;

	int value = identTable->size();

	(*this->identTable)[tempIdentName] = value;
	this->revLookupTable->push_back(tempIdentName);

	std::cout << "inserted: " << tempIdentName <<":" << value << std::endl;
	return put(&tempIdentName);
}

int IdentTable::getValue(String * identName){
	return put(identName);
}

int IdentTable::getValue(char * identName){
	return put(identName);
}

String IdentTable::getName(int identValue){
	return (*revLookupTable)[identValue];
}

void IdentTable::show() {
	std::cout << "** Table Identificateur" << std::endl;

	for (MapStrInt::iterator it = identTable->begin(); it != identTable->end(); it++) {
		const std::string &name = it->first;
		int id = it->second;
		std::cout << name  << " " << id << std::endl;
	}

}
